package com.server.common.mailbox;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.server.common.code.error.BusinessException;
import com.server.common.mailbox.config.MailConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.*;

@Slf4j
public class MailServiceImpl  {

    private final MailConfig mailConfig = SpringUtil.getBean(MailConfig.class);

    private Session session;

    private final List<String> toAddressList = new ArrayList<>();

    private final MimeMultipart mimeMultipart = new MimeMultipart();

    private String title = "标题";

    private String fromAddress;

    private final List<File> fileList = new ArrayList<>();

    private String content = "内容";

    private String type = "";

    // 邮件服务器地址
    private String host = "";

    // 邮件服务器端口
    private Integer port = 80;

    // 发件人的用户名
    private String userName = "";

    // 发件人密码
    private String passWord = "";

    private String aliasName = "";

    public MailServiceImpl(){
        host = mailConfig.getHost();
        port = mailConfig.getPort();
        aliasName = mailConfig.getAliasName();
        userName = mailConfig.getUserName();
        passWord = mailConfig.getPassWord();
    }

    public static MailServiceImpl builder(){
        return new MailServiceImpl();
    }

    public MailServiceImpl smtpSession(){
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.port", port);
            session =  Session.getInstance(props);
        }catch (Exception e){
            log.error("配置失败",e);
            throw new BusinessException("配置失败",e);
        }
        return this;
    }

    public MailServiceImpl setTitle(String title){
        this.title = title;
        return this;
    }

    public MailServiceImpl setAliasName(String aliasName){
        this.aliasName = aliasName;
        return this;
    }

    public MailServiceImpl setUserName(String userName){
        this.userName = userName;
        return this;
    }

    public MailServiceImpl setPassWord(String passWord){
        this.passWord = passWord;
        return this;
    }

    public MailServiceImpl setHost(String host){
        this.host = host;
        return this;
    }

    public MailServiceImpl setPort(Integer port){
        this.port = port;
        return this;
    }

    public MailServiceImpl setFromAddress(String fromAddress){
        this.fromAddress = fromAddress;
        return this;
    }

    public MailServiceImpl addRecipients(String toAddress){
        toAddressList.add(toAddress);
        return this;
    }

    public MailServiceImpl setContent(String content,String type){
        this.content = content;
        this.type = type;
        return this;
    }

    public MailServiceImpl addFile(File file){
        fileList.add(file);
        return this;
    }

    public void send() {
        try {
            MimeMessage message = new MimeMessage(session);

            message.setSubject(title);

            // 设置邮件发送日期
            message.setSentDate(new Date());

            // 设置邮件发送者的地址
            message.setFrom(new InternetAddress(fromAddress, aliasName));

            //
            message.setRecipients(Message.RecipientType.CC,InternetAddress.parse(StrUtil.join(",",toAddressList)));

            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setContent(content, type);
            mimeMultipart.addBodyPart(bodyPart);

            for (File file:fileList){
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
                mimeBodyPart.setFileName(MimeUtility.encodeText(file.getName(), "utf-8", null));
                mimeMultipart.addBodyPart(mimeBodyPart);
            }

            message.setContent(mimeMultipart);

            message.saveChanges();

            send(session,message);

        }catch (Exception e){
            log.error("发送",e);
            throw new BusinessException("发送",e);
        }
    }

    public void send(Session session,Message message){
        Transport transport = null;
        try {
            transport = session.getTransport();
            transport.connect(host,port, userName, passWord);
            transport.sendMessage(message, message.getAllRecipients());
        }catch (Exception e){
            log.error("发送",e);
        }finally {
            if(ObjectUtils.isEmpty(transport)){
                return;
            }

            try {
                transport.close();
            }catch (Exception e){
                log.error("发送",e);
            }

        }
    }
}
